import { defineStore } from 'pinia';
import { store } from '@/stores';
import { useApi } from '@/hooks/useApi';
import { useUserStoreOut } from '@/stores/modules/user';
import { ResultEnum } from '@/enums/httpEnum';
import { commonApiWithOutComponent } from '@/utils';
import type { RouteRecordRaw } from 'vue-router';

type AsideMenu = {
  collectedSongMenuList: any[];
  collectedSongMenuListHasMore: boolean;
};

interface IAppStoreState {
  themeMode: TModeUnit;
  asideMenu: AsideMenu;
  currentMenuRoute: Partial<RouteRecordRaw>;
}

export type TModeUnit = 'default-theme';

const { user: userApi } = useApi();

const { to: $to, message: $message } = commonApiWithOutComponent();

export const useAppStore = defineStore({
  id: 'app',
  state: (): IAppStoreState => ({
    themeMode: 'default-theme',
    asideMenu: {
      collectedSongMenuList: [],
      collectedSongMenuListHasMore: true,
    },
    currentMenuRoute: {},
  }),
  getters: {
    collectedSongMenuList(): any[] {
      return this.asideMenu.collectedSongMenuList;
    },
    collectedSongListHasMore(): boolean {
      return this.asideMenu.collectedSongMenuListHasMore;
    },
    getCurrentMenuRoute(state): Partial<RouteRecordRaw> {
      return state.currentMenuRoute;
    },
  },
  actions: {
    async updateCollectedMenuList(limit = 30, offset = 0) {
      const { userId } = useUserStoreOut();
      const [error, resp]: [any, any] = await $to(userApi.playList(limit, offset, userId));
      if (error || resp.code !== ResultEnum.SUCCESS) {
        $message.error(resp?.msg || error?.msg || error || '');
      }
      if (resp && resp.code === ResultEnum.SUCCESS) {
        const { playlist, more } = resp;
        this.asideMenu.collectedSongMenuList = playlist;
        this.asideMenu.collectedSongMenuListHasMore = more;
      }
    },
  },
});

// @ts-ignore
export const useAppStoreOut = () => useAppStore(store);
